import type { configType, stateInter } from '@/types/hooks/addDia'
import type { UnwrapRef } from 'vue'
export function diaApi<T>(config: configType<T>) {
  const { apis, emit } = config
  if (!config.editKey) {
    config.editKey = 'id'
  }
  const state = reactive<stateInter<T>>({
    dialogFormVisible: false,
    title: '',
    queryForm: {} as T,
  })
  if (config?.queryForm) {
    state.queryForm = deepClone(config.queryForm)
  }

  const handleValidateClick = async (e: MouseEvent) => {
    e.preventDefault()
    try {
      await config.ruleForm.value?.validate()
      save()
    } catch (error) {
      if (config?.errorTip) {
        config.errorTip(error)
      }
      return
    }
  }
  let requestLoading = false
  const save = async () => {
    let params = toRaw(state.queryForm)
    if (config?.saveParams) {
      params = config.saveParams(params)
    }
    if (requestLoading) return
    requestLoading = true
    if (apis) {
      try {
        if (
          config.editKey &&
          Object.keys(params).includes(config.editKey) &&
          params[config.editKey]
        ) {
          delete params.delFlag
          const { code, msg } = await apis.doEdit.api(params)
          if (code !== 0) {
            requestLoading = false
            msgUtil.$message.error(msg)
            return
          }
          requestLoading = false
          emit('edit', params)
          msgUtil.$message.success(apis.doEdit?.successText || '编辑成功')
        } else {
          const { code, msg } = await apis.doAdd.api(params)
          if (code !== 0) {
            requestLoading = false
            msgUtil.$message.error(msg)
            return
          }
          requestLoading = false
          emit('add', params)
          msgUtil.$message.success(apis.doAdd?.successText || '添加成功')
        }
        emit('success', params)
        close()
      } catch (e) {
        console.log(e)
        requestLoading = false
      }
    }
  }

  const open = (row) => {
    if (row) {
      if (config.editKey) {
        state.title = row?.[config.editKey] ? '编辑' : '添加'
      } else {
        state.title = '添加'
      }
      state.queryForm = Object.assign({}, row)
    } else {
      state.title = '添加'
    }
    state.dialogFormVisible = true
    if (config?.showEdit) {
      config.showEdit()
    }
  }

  const close = () => {
    if (config?.ruleForm) {
      config?.ruleForm.value?.restoreValidation()
    }
    if (config.queryForm) {
      state.queryForm = deepClone(config.queryForm)
    } else {
      state.queryForm = {} as UnwrapRef<T>
    }
    if (config?.closeExtend) {
      config.closeExtend()
    }
    state.dialogFormVisible = false
  }

  return {
    ...toRefs(state),
    open,
    close,
    handleValidateClick,
  }
}
